import librosa
import wave
import contextlib
 
def get_duration_wav(file_path):
    """
    获取wav音频文件时长
    :param file_path:
    :return:
    """
    with contextlib.closing(wave.open(file_path, 'r')) as f:
        frames = f.getnframes()
        rate = f.getframerate()
        duration = frames / float(rate)
    return duration
 
 
def get_duration_mp3_and_wav(file_path):
     """
     获取mp3/wav音频文件时长
     :param file_path:
     :return:
     """
     duration = librosa.get_duration(filename=file_path)
     return duration
 
if __name__ == "__main__":
    file_path = r'data_CTC\words\beijing\beijing (5).wav'

    # 仅wav
    duration = get_duration_wav(file_path)
    print(f'duration = {duration}')

    # mp3 和 wav 均可
    duration = get_duration_mp3_and_wav(file_path)
 
    print(f'duration = {duration}')
